import 'package:flutter/material.dart';
import 'package:flutter_deer/database/beans/get_user_info_entity.dart';
import 'package:flutter_deer/database/beans/member/card_list_bean_entity.dart';
import 'package:flutter_deer/database/beans/member_bean_entity.dart';
import 'package:flutter_deer/mvvm/base_net_provider.dart';
import 'package:flutter_deer/net/dio_utils.dart';
import 'package:flutter_deer/net/http_api.dart';
import 'package:flutter_deer/util/input_formatter/mny_format.dart';
import 'package:flutter_deer/util/toast_utils.dart';
import 'package:get/get.dart';

class MemberProvider extends BaseNetProvider {
  final Rx<MemberBeanMembers?> mUser = Rx<MemberBeanMembers?>(null);

  /// 根据手机号请求会员信息
  void requestMemberInfo({String? phone, String? cardNo, String? uuId, void Function()? onGiftCard}) {
    final Map<String, String> params = <String, String>{};
    params['businessType'] = 'LOGIN';
    params['phone'] = phone ?? '';
    params['encryptedStr'] = cardNo ?? '';
    params['cardId'] = uuId ?? '';
    // params['plateNo'] = '';
    // params['memberCode'] = '';
    asyncRequestNetwork<MemberBeanEntity>(
      Method.get,
      url: HttpApi.getMember,
      queryParameters: params,
      onSuccess: (data) {
        // 如果是礼品卡
        if (data?.memberAccount != null && data?.memberAccount is Map<String, dynamic>) {
          mUser.value = null;
          onGiftCard?.call();
          Toast.show('礼品卡不可充值管理');
          return;
        }
        if (data?.members?.isNotEmpty != true) {
          Toast.show('会员不存在');
          return;
        }

        if ((data?.members?.length ?? 0) > 1) {
          showSelectList(data?.members ?? []);
        } else {
          mUser.value = data?.members?.firstOrNull;
        }
      },
    );
  }

  // 展示多选列表
  void showSelectList(List<MemberBeanMembers> members) {
    Get.dialog<void>(AlertDialog(
      title: const Text('选择会员'),
      content: SizedBox(
        width: 300,
        height: 300,
        child: ListView.builder(
          itemCount: members.length,
          itemBuilder: (context, index) {
            final member = members[index];
            return Material(
              color: Colors.transparent,
              child: InkWell(
                onTap: () {
                  mUser.value = member;
                  Get.back<void>(); // 关闭对话框
                },
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                  decoration: const BoxDecoration(
                      border: Border(
                    bottom: BorderSide(color: Colors.grey, width: 0.5),
                  )),
                  child: Row(
                    children: [
                      // 显示会员姓名
                      Text('${member.phone?.phone}', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500)),
                      const SizedBox(width: 10),
                      // 显示会员手机号（如果存在）
                      Text('${member.nickname}', style: const TextStyle(fontSize: 14, color: Colors.grey)),
                    ],
                  ),
                ),
              ),
            );
          },
        ),
      ),
    ));
  }

  /// 个人中心
  void requestIndividualAccountPage({String? mchMemberId, String? phone, void Function(List<CardListBeanEntity>?)? onSuccess}) {
    asyncRequestNetwork<List<CardListBeanEntity>>(
      Method.post,
      url: HttpApi.individualAccountPage,
      params: {
        'mchMemberId': mchMemberId ?? '',
        'phone': phone ?? '',
        'mchCode': GetUserInfoEntity.get()?.loginMerchantCode?? '',
        'groupMchCode': GetUserInfoEntity.get()?.groupMerchantCode?? '',
      },
      onSuccess: (data) {
        onSuccess?.call(data);
      },
    );
  }
}
